﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyERP.Models;

namespace MyERP.WebApi
{
    [Route("api/[controller]/[Action]")]
    [ApiController]
    [Authorize(Roles = "admin,q3")]
    public class SalesTicketController : ControllerBase
    {
        private readonly MyDbContext db;
        public SalesTicketController(MyDbContext myDbContext)
        {
            db = myDbContext;
        }
        /// <summary>
        /// 查询单个订单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ActionResult<SalesTicket>> One(string id)
        {
            SalesTicket? p = await db.SalesTicket.FirstOrDefaultAsync(w => w.Id == id);
            if (p == null)
            {
                return NotFound($"ID为{id}的订单不存在");
            }
            return p;
        }
        /// <summary>
        /// 添加销售单
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> Add([FromBody] TempSales data)
        {
            SalesTicket po = new SalesTicket();

            //查询数据库今日是否存在单据，用作生成单号
            DateTime today = DateTime.Today;
            bool exists = db.SalesTicket.Any(x => x.DateTimeNow.Date == today);
            if (!exists)
            {
                po.Id = today.ToString("yyyyMMdd-") + "001";
            }
            else
            {
                // 查询最后一条记录
                var d = db.SalesTicket
                    .OrderByDescending(o => o.DateTimeNow)
                    .FirstOrDefault();
                string dId = d.Id;
                int i = Convert.ToInt32(dId.Substring(dId.Length - 3));
                i++;
                po.Id = today.ToString("yyyyMMdd-") + i.ToString("D3");
            }

            //格式化日期
            DateTime time;
            if (DateTime.TryParse(data.Datetime, out time))
            {
                po.CreateDateTime = time;
            }
            else
            {
                po.CreateDateTime = DateTime.Now;
            }

            po.ClientName = data.ClientName;
            po.GoodsName = data.GoodsName;
            po.Number = data.Number;
            po.Price = data.Price;
            po.Money = data.Money;

            db.SalesTicket.Add(po);
            await db.SaveChangesAsync();

            return Ok();
        }

        /// <summary>
        /// 返回所有销售单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> All(int page = 1, int pageSize = 15, string? startDate = null, string? endDate = null, string? clientName = null, string? goodsName = null)
        {
            var query = db.SalesTicket.AsQueryable();

            // 根据供应商筛选数据
            if (!string.IsNullOrEmpty(clientName))
            {
                query = query.Where(p => p.ClientName == clientName);
            }
            // 根据物品筛选数据
            if (!string.IsNullOrEmpty(goodsName))
            {
                query = query.Where(p => p.GoodsName == goodsName);
            }

            //如果没有传递日期范围，默认查询今日的数据
            if (string.IsNullOrEmpty(startDate) && string.IsNullOrEmpty(endDate))
            {
                var today = DateTime.Today;
                startDate = today.ToString("yyyy-MM-dd");
                endDate = today.ToString("yyyy-MM-dd");
            }

            // 解析日期范围
            DateTime startDateTime = DateTime.Parse(startDate); // 开始日期（00:00:00）
            DateTime endDateTime = DateTime.Parse(endDate).AddDays(1).AddSeconds(-1); // 结束日期（23:59:59）

            // 根据日期范围过滤数据
            query = query.Where(p => p.CreateDateTime >= startDateTime && p.CreateDateTime <= endDateTime);

            int totalCount = await query.CountAsync();
            var salesTickets = await query
                .OrderByDescending(p => p.Id)   //倒序
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();
            return Ok(new
            {
                totalCount = totalCount,
                page = page,
                pageSize = pageSize,
                salesTickets = salesTickets
            });
        }

        /// <summary>
        /// 修改销售单
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> Edit([FromBody] TempSales data)
        {
            SalesTicket? po = db.SalesTicket.FirstOrDefault(a => a.Id == data.Id);
            if (po == null)
            {
                return NotFound();
            }

            DateTime time;
            if (DateTime.TryParse(data.Datetime, out time))
            {
                po.CreateDateTime = time;
            }
            else
            {
                po.CreateDateTime = DateTime.Now;
            }

            po.ClientName = data.ClientName;
            po.GoodsName = data.GoodsName;
            po.Number = data.Number;
            po.Price = data.Price;
            po.Money = data.Money;

            await db.SaveChangesAsync();
            return Ok();
        }

        /// <summary>
        /// 删除销售单
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ActionResult> Del(string? id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return NotFound();
            }
            SalesTicket? po = db.SalesTicket.FirstOrDefault(a => a.Id == id);
            if (po == null)
            {
                return NotFound();
            }
            db.Remove(po);
            await db.SaveChangesAsync();
            return Ok();
        }
        
    }
    public class TempSales
    {
        public string Id { get; set; }
        public string Datetime { get; set; }
        public string ClientName { get; set; }
        public string GoodsName { get; set; }
        public int Number { get; set; }
        public double Price { get; set; }
        public double Money { get; set; }
    }
    /// <summary>
    /// 模型：每月销售摘要
    /// </summary>
    public class MonthlySalesSummary
    {
        public int Year { get; set; } // 年份
        public int Month { get; set; } // 月份
        public double TotalAmount { get; set; } // 总金额
    }
}
